import requests
import json
import re
import time

# headers = {
#     "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0",
#     "Content-Type": "application/json; charset=UTF-8",
#     "Cookie": "hash_key=khztnheyrqcabdtb",
# }

# 新的headers
headers = {
    "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0",
    "Content-Type": "application/json; charset=UTF-8",
    "Cookie": "hash_key=ovsnpegalqegeyza",
}


def get_EU_ID():
    url = "http://192.168.5.100:8400/public/cgi-bin/home.cgi"  # 替换为实际的接口地址
    data = {
        "page": 1,
        "limit": 20,
        "flag": "get_RUIndex_list",
        "account": "root",
        "sessionid": "CZTJYZHTWBXADWRH",
        "sear": "Device.Services.FAPService.1.CellConfig.1",
        "EU_indexid": 1
    }
    # 发送 POST 请求
    response = requests.post(url, json=data)
    # 打印响应
    if response.status_code == 200:
        # 尝试解析 JSON 数据
        try:
            response_data = response.json()
            # 提取 rows 中的 RU_indexid 值
            rows = response_data.get("rows", [])
            if rows and "RU_indexid" in rows[0]:
                return rows[0]["RU_indexid"]
            else:
                return "RU_indexid 不存在或 rows 为空"
        except ValueError:
            return "响应不是有效的 JSON 格式"
    else:
        return f"请求失败，状态码: {response.status_code}"


def getspeed_on():
    # 定义请求的 URL 和数据
    url = "http://192.168.5.100:8400/public/cgi-bin/rate.cgi"  # 替换为实际的接口地址
    data = {
        "flag": "rateSwitch",
        "switchValue": 1,
        "page": 1,
        "limit": 20,
        "account": "root",
        "sessionid": "CZTJYZHTWBXADWRH",
        "sear": "Device.Services.FAPService.1.CellConfig.1",
        "EU_indexid": 1
    }

    try:
        # 发送 POST 请求
        response = requests.post(url, headers=headers, data=data)
    except requests.exceptions.RequestException as e:
        # 发生请求异常时输出状态码并返回异常信息
        print(f"HTTP请求失败: {e}")


def action(option, para="1"):
    """
    :param option: 选择需要发送的内容
    :param para: 输入需要修改参数的值，可以为整数时间格式或者是字符串
    :return:
    """
    if option == "get_MaxTxPower_info":  # 获取小区最大发射功率
        url = "http://192.168.5.100:8400/public/cgi-bin/overall.cgi"
        data = {
            "page": "1",
            "limit": "20",
            "flag": "get_MaxTxPower_info",
            "account": "root",
            "sessionid": "CZTJYZHTWBXADWRH",
            "sear": "Device.Services.FAPService.1.CellConfig.1"
        }
        target1 = "MaxTxPower"
        target2 = "Null"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)

            # 如果状态码不是 200，表示请求失败
            if response.status_code != 200:
                print(f"Status Code: {response.status_code}")
                raise ValueError(f"请求失败，状态码：{response.status_code}")

            # 解析 JSON 响应
            response_json = response.json()
            result = []

            # 如果 option 为 "Read_Home"，处理特定的 "ueArrOdiResponse"
            if option == "Read_Home":
                print(response_json['data']['ueArrOdiResponse'])
                return result  # 返回空数组

            # 如果是其他情况，根据目标字段提取数据
            if target1 == "msg":
                print("msg:", response_json["msg"])
            else:
                value1 = int(response_json['data'][target1])  # 转换为整数
                result.append(value1)

            if target2 != "Null":
                value2 = int(response_json['data'][target2])  # 转换为整数
                result.append(value2)

            if target3 != "Null":
                value3 = int(response_json['data'][target3])  # 转换为整数
                result.append(value3)

            return result  # 返回提取的数据数组

        except requests.exceptions.RequestException as e:
            # 如果发生网络请求错误，输出异常信息并返回错误信息
            return f"HTTP请求失败: {e}"

        except KeyError as ke:
            # 如果响应中缺少预期的字段，输出缺失字段并返回错误信息
            return f"响应中缺少字段: {ke}"

        except ValueError as ve:
            # 如果值转换失败，返回值转换错误信息
            return f"值转换错误: {ve}"

    if option == "set_MaxTxPower_info":  # 修改小区最大发射功率,范围为18-24
        url = "http://192.168.5.100:8400/public/cgi-bin/overall.cgi"
        data = {
            "flag": "set_MaxTxPower_info",
            "sessionid": "CZTJYZHTWBXADWRH",
            "account": "root",
            "sear": "Device.Services.FAPService.1.CellConfig.1",
            "MaxTxPower": para,
            "value": para,
            "key": "MaxTxPower"
        }
        target1 = "msg"
        target2 = "Null"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)

            # 仅在请求失败时输出状态码
            if response.status_code != 200:
                print(f"Status Code: {response.status_code}")
                raise ValueError(f"请求失败，状态码：{response.status_code}")

            # 解析 JSON 响应
            response_json = response.json()

            # 处理 option 为 "Read_Home" 时的情况
            if option == "Read_Home":
                ue_arr_odi_response = response_json['data']['ueArrOdiResponse']
                print(ue_arr_odi_response)  # 打印出 ueArrOdiResponse 数据
            else:
                # 输出 msg 字段
                print("msg:", response_json["msg"])

        except requests.exceptions.RequestException as e:
            # 发生请求异常时输出状态码并返回异常信息
            print(f"HTTP请求失败: {e}")

    if option == "get_RU_info":  # 获取RU的信息状态
        id_number = get_EU_ID()
        url = "http://192.168.5.100:8400/public/cgi-bin/home.cgi"
        data = {
            "page": "1",
            "limit": "20",
            "flag": "get_RU_info",
            "account": "root",
            "sessionid": "CZTJYZHTWBXADWRH",
            "sear": "Device.Services.FAPService.1.CellConfig.1",
            "EU_indexid": "1",
            "RU_indexid": id_number,
            "RU": "more",
            "AdminExist": "1",
            "OptId": "1",
            "Status": "1"
        }
        target1 = "PowerSupplySwitch"
        target2 = "RFTxStatus"
        target3 = "Status"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)

            # 如果状态码不是 200，表示请求失败
            if response.status_code != 200:
                print(f"Status Code: {response.status_code}")
                raise ValueError(f"请求失败，状态码：{response.status_code}")

            # 解析 JSON 响应
            response_json = response.json()
            result = []

            # 如果 option 为 "Read_Home"，处理特定的 "ueArrOdiResponse"
            if option == "Read_Home":
                print(response_json['data']['ueArrOdiResponse'])
                return result  # 返回空数组

            # 如果是其他情况，根据目标字段提取数据
            if target1 == "msg":
                print("msg:", response_json["msg"])
            else:
                value1 = int(response_json['data'][target1])  # 转换为整数
                result.append(value1)

            if target2 != "Null":
                value2 = int(response_json['data'][target2])  # 转换为整数
                result.append(value2)

            if target3 != "Null":
                value3 = int(response_json['data'][target3])  # 转换为整数
                result.append(value3)

            return result  # 返回提取的数据数组

        except requests.exceptions.RequestException as e:
            # 如果发生网络请求错误，输出异常信息并返回错误信息
            return f"HTTP请求失败: {e}"

        except KeyError as ke:
            # 如果响应中缺少预期的字段，输出缺失字段并返回错误信息
            return f"响应中缺少字段: {ke}"

        except ValueError as ve:
            # 如果值转换失败，返回值转换错误信息
            return f"值转换错误: {ve}"

    if option == "set_RF_status":  # 设置射频状态，0为关闭，1为开启
        id_number = get_EU_ID()
        url = "http://192.168.5.100:8400/public/cgi-bin/home.cgi"
        data = {
            "flag": "set_RU_info",
            "sessionid": "CZTJYZHTWBXADWRH",
            "account": "root",
            "sear": "Device.Services.FAPService.1.CellConfig.1",
            "RU_indexid": id_number,
            "RouteIndex": "1+1",
            "SoftwareVersion": "0.05.67",
            "Status": "1",
            "Reboot": "0",
            "RFTxStatus": para,  # Turn off RF transmission status
            "Level": "2",
            "DeviceId": "2",
            "OptId": "1",
            "AdminExist": "1",
            "Location": "",
            "UserLabel": "SG-SA-GNB",
            "VendorUnitFamilyType": "RU",
            "VendorUnitTypeNumber": "0001",
            "ManufacturerOUI": "8CE468",
            "Manufacturer": "NR-gNB",
            "ProvisioningCode": "NR-gNB",
            "ModelName": "AI-PRRU-B10R",
            "SerialNumber": "AI-RW230526-2069",
            "HardwareVersion": "1738V01",
            "SwUpgrade_Stage": "5",
            "SwUpgrade_Status": "1",
            "SwUpgrade_FailureCause": "",
            "UpgradeEnable": "0",
            "FrequencyBand": "",
            "DateOfManufacture": "2020-06-17T00:00:00Z",
            "DLCRCSum": "0.000000000",
            "ULCRCSum": "0.000000000",
            "PowerSupplySwitch": "1",
            "EU_indexid": "1",
            "value": para,
            "key": "RFTxStatus"
        }
        target1 = "msg"
        target2 = "Null"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)

            # 仅在请求失败时输出状态码
            if response.status_code != 200:
                print(f"Status Code: {response.status_code}")
                raise ValueError(f"请求失败，状态码：{response.status_code}")

            # 解析 JSON 响应
            response_json = response.json()

            # 处理 option 为 "Read_Home" 时的情况
            if option == "Read_Home":
                ue_arr_odi_response = response_json['data']['ueArrOdiResponse']
                print(ue_arr_odi_response)  # 打印出 ueArrOdiResponse 数据
            else:
                # 输出 msg 字段
                print("msg:", response_json["msg"])

        except requests.exceptions.RequestException as e:
            # 发生请求异常时输出状态码并返回异常信息
            print(f"HTTP请求失败: {e}")

    if option == "set_RRU_power":  # 控制天线的开关，0为关，1为开
        id_number = get_EU_ID()
        url = "http://192.168.5.100:8400/public/cgi-bin/home.cgi"
        data = {
            "flag": "set_RU_info",
            "sessionid": "CZTJYZHTWBXADWRH",
            "account": "root",
            "sear": "Device.Services.FAPService.1.CellConfig.1",
            "RU_indexid": id_number,
            "RouteIndex": "1+1",
            "SoftwareVersion": "0.05.67",
            "Status": "1",
            "Reboot": "0",
            "RFTxStatus": "1",  # 射频传输状态开启
            "Level": "2",
            "DeviceId": "2",
            "OptId": "1",
            "AdminExist": "1",
            "Location": "",
            "UserLabel": "SG-SA-GNB",
            "VendorUnitFamilyType": "RU",
            "VendorUnitTypeNumber": "0001",
            "ManufacturerOUI": "8CE468",
            "Manufacturer": "NR-gNB",
            "ProvisioningCode": "NR-gNB",
            "ModelName": "AI-PRRU-B10R",
            "SerialNumber": "AI-RW230526-2069",
            "HardwareVersion": "1738V01",
            "SwUpgrade_Stage": "5",
            "SwUpgrade_Status": "1",
            "SwUpgrade_FailureCause": "",
            "UpgradeEnable": "0",
            "FrequencyBand": "",
            "DateOfManufacture": "2020-06-17T00:00:00Z",
            "DLCRCSum": "0.000000000",
            "ULCRCSum": "0.000000000",
            "PowerSupplySwitch": para,  # 电源开关关闭
            "EU_indexid": "1",
            "value": para,  # 操作值为0，关闭电源
            "key": "PowerSupplySwitch"  # 键为PowerSupplySwitch，表示操作电源开关
        }
        target1 = "msg"
        target2 = "Null"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)

            # 仅在请求失败时输出状态码
            if response.status_code != 200:
                print(f"Status Code: {response.status_code}")
                raise ValueError(f"请求失败，状态码：{response.status_code}")

            # 解析 JSON 响应
            response_json = response.json()

            # 处理 option 为 "Read_Home" 时的情况
            if option == "Read_Home":
                ue_arr_odi_response = response_json['data']['ueArrOdiResponse']
                print(ue_arr_odi_response)  # 打印出 ueArrOdiResponse 数据
            else:
                # 输出 msg 字段
                print("msg:", response_json["msg"])

        except requests.exceptions.RequestException as e:
            # 发生请求异常时输出状态码并返回异常信息
            print(f"HTTP请求失败: {e}")

    if option == "get_EnergySave_info":  # 获取基站休眠信息
        url = "http://192.168.5.100:8400/public/cgi-bin/overall.cgi"
        data = {
            "page": "1",
            "limit": "20",
            "flag": "get_EnergySaveParam_info",
            "account": "root",
            "sessionid": "CZTJYZHTWBXADWRH",
            "sear": "Device.Services.FAPService.1.CellConfig.1"
        }
        target1 = "EnergySavingTime"
        target2 = "EnergySavingType"
        target3 = "EnergySavingStage"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)

            # 检查响应状态码
            print(f"Status Code: {response.status_code}")
            if response.status_code != 200:
                raise ValueError(f"请求失败，状态码：{response.status_code}")

            # 解析 JSON 响应
            response_json = response.json()

            # 提取目标字段值
            energy_saving_time = response_json['data'][target1]
            energy_saving_type = response_json['data'][target2]
            energy_saving_stage = int(response_json['data'][target3])  # 转换为整型

            # 返回结果列表
            return [energy_saving_time, energy_saving_type, energy_saving_stage]

        except requests.exceptions.RequestException as e:
            print(f"HTTP请求失败: {e}")
            return None
        except KeyError as ke:
            print(f"响应中缺少字段: {ke}")
            return None
        except ValueError as ve:
            print(f"值错误: {ve}")
            return None

    if option == "set_EnergySave_time":  # 修改基站休眠时间
        url = "http://192.168.5.100:8400/public/cgi-bin/overall.cgi"
        data = {
            "flag": "set_EnergySaveParam_info",
            "sessionid": "CZTJYZHTWBXADWRH",
            "account": "root",
            "sear": "Device.Services.FAPService.1.CellConfig.1",
            "EnergySavingType": "NOT_SAVING",
            "EnergySavingTime": para,  # 例如"17:43:00-17:44:59"
            "EnergySavingDelayTime": "0",
            "PrbLowThreshold": "50",
            "EnergySavingStage": "未进行休眠",
            "RRCLowThreshold": "100",
            "AutoXnCellActivationEnable": "0",
            "value": para,
            "key": "EnergySavingTime"
        }
        target1 = "msg"
        target2 = "Null"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)

            # 仅在请求失败时输出状态码
            if response.status_code != 200:
                print(f"Status Code: {response.status_code}")
                raise ValueError(f"请求失败，状态码：{response.status_code}")

            # 解析 JSON 响应
            response_json = response.json()

            # 处理 option 为 "Read_Home" 时的情况
            if option == "Read_Home":
                ue_arr_odi_response = response_json['data']['ueArrOdiResponse']
                print(ue_arr_odi_response)  # 打印出 ueArrOdiResponse 数据
            else:
                # 输出 msg 字段
                print("msg:", response_json["msg"])

        except requests.exceptions.RequestException as e:
            # 发生请求异常时输出状态码并返回异常信息
            print(f"HTTP请求失败: {e}")

    if option == "set_EnergySave_type":  # 修改基站休眠策略,0代表无休眠，1代表深度休眠
        url = "http://192.168.5.100:8400/public/cgi-bin/overall.cgi"
        if para == "0":
            data = {
                "flag": "set_EnergySaveParam_info",
                "sessionid": "CZTJYZHTWBXADWRH",
                "account": "root",
                "sear": "Device.Services.FAPService.1.CellConfig.1",
                "EnergySavingType": "NOT_SAVING",  # 修改基站休眠策略，"DEEP_SAVING" 和 “NOT_SAVING”
                "EnergySavingTime": "16:43:00-16:44:59",
                "EnergySavingDelayTime": "0",
                "PrbLowThreshold": "50",
                "EnergySavingStage": "未进行休眠",
                "RRCLowThreshold": "100",
                "AutoXnCellActivationEnable": "0",
                "value": "NOT_SAVING",
                "key": "EnergySavingType"
            }
        if para == "1":
            data = {
                "flag": "set_EnergySaveParam_info",
                "sessionid": "CZTJYZHTWBXADWRH",
                "account": "root",
                "sear": "Device.Services.FAPService.1.CellConfig.1",
                "EnergySavingType": "DEEP_SAVING",  # 修改基站休眠策略，"DEEP_SAVING" 和 “NOT_SAVING”
                "EnergySavingTime": "16:43:00-16:44:59",
                "EnergySavingDelayTime": "0",
                "PrbLowThreshold": "50",
                "EnergySavingStage": "未进行休眠",
                "RRCLowThreshold": "100",
                "AutoXnCellActivationEnable": "0",
                "value": "DEEP_SAVING",
                "key": "EnergySavingType"
            }
        target1 = "msg"
        target2 = "Null"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)

            # 仅在请求失败时输出状态码
            if response.status_code != 200:
                print(f"Status Code: {response.status_code}")
                raise ValueError(f"请求失败，状态码：{response.status_code}")

            # 解析 JSON 响应
            response_json = response.json()

            # 处理 option 为 "Read_Home" 时的情况
            if option == "Read_Home":
                ue_arr_odi_response = response_json['data']['ueArrOdiResponse']
                print(ue_arr_odi_response)  # 打印出 ueArrOdiResponse 数据
            else:
                # 输出 msg 字段
                print("msg:", response_json["msg"])

        except requests.exceptions.RequestException as e:
            # 发生请求异常时输出状态码并返回异常信息
            print(f"HTTP请求失败: {e}")

    if option == "get_Bandwidth_info":
        url = "http://192.168.5.100:8400/public/cgi-bin/overall.cgi"
        data = {
            'page': '1',
            'limit': '20',
            'flag': 'get_CellConfig_info',
            'account': 'root',
            'sessionid': 'CZTJYZHTWBXADWRH',
            'sear': 'Device.Services.FAPService.1.CellConfig.1',  # 如果需要可以取消注释
        }
        target1 = "ULBandwidth"
        target2 = "DLBandwidth"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)

            # 如果请求状态码不是 200，抛出异常
            if response.status_code != 200:
                raise ValueError(f"请求失败，状态码：{response.status_code}")

            # 解析 JSON 响应
            response_json = response.json()
            result = []

            # 如果 option 是 "Read_Home" ，处理特定数据
            if option == "Read_Home":
                ue_arr_odi_response = response_json['data']['ueArrOdiResponse']
                print(ue_arr_odi_response)  # 打印出 ueArrOdiResponse 数据
                return result  # 只返回空数组

            # 否则处理 target1, target2, target3
            if target1 == "msg":
                print("msg: " + response_json["msg"])
            else:
                # 提取 target1 的值并转换为整型
                value1 = int(response_json['data'][target1])
                result.append(value1)

            if target2 != "Null":
                # 提取 target2 的值并转换为整型
                value2 = int(response_json['data'][target2])
                result.append(value2)

            if target3 != "Null":
                # 提取 target3 的值并转换为整型
                value3 = int(response_json['data'][target3])
                result.append(value3)

            return result  # 返回结果

        except requests.exceptions.RequestException as e:
            # 请求异常时返回异常信息
            return f"HTTP请求失败: {e}"
        except KeyError as ke:
            # 响应中缺少字段时，返回异常信息
            return f"响应中缺少字段: {ke}"
        except ValueError as ve:
            # 处理值错误时返回异常信息
            return f"值错误: {ve}"

    if option == "Read_Home":
        url = "http://192.168.5.100:8400/public/cgi-bin/information.cgi"
        data = {
            "flag": "get_runstatus_info",
        }
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)

            # 正常情况下不输出 Status Code，只有在异常时输出
            if response.status_code != 200:
                raise ValueError(f"请求失败，状态码：{response.status_code}")

            # 解析 JSON 响应
            response_json = response.json()

            # 当 option 为 "Read_Home" 时，处理数据
            if option == "Read_Home":
                ue_list = response_json['data']['ueArrOdiResponse']
                # print("ue_list:", ue_list)  # 打印出 ue_list 数据以供检查
                # 提取 ueCount 值并转换为整型
                result = [int(item['ueCount']) for item in ue_list if 'ueCount' in item]
                return result  # 返回结果

        except requests.exceptions.RequestException as e:
            # 请求异常时返回异常信息
            return f"HTTP请求失败: {e}"

        except KeyError as ke:
            # 响应中缺少字段时，返回异常信息
            return f"响应中缺少字段: {ke}"

        except ValueError as ve:
            # 处理值错误时返回异常信息
            return f"值错误: {ve}"

    if option == "set_Absolute_SSB":
        url = "http://192.168.5.100:8400/public/cgi-bin/generalParameters.cgi"
        data = {
            "flag": "set_FAP_info",
            "sessionid": "CZTJYZHTWBXADWRH",
            "account": "root",
            "sear": "Device.Services.FAPService.1.CellConfig.1",
            "PhyCellID": "100",
            "CellIdWithinGnb": "1",
            "UlLayers": "0",
            "UlAntennas": "4",
            "DlLayers": "0",
            "DlAntennas": "4",
            "PdschMcsTable": "qam256",
            "PuschMcsTable": "qam256",
            "NRARFCNDL": "513000",
            "NRARFCNUL": "513000",
            "AbsoluteFrequencySSB": para,
            "SsbPower": "-11",
            "FreqBandIndicator": "41",
            "TA": "more",
            "value": para,
            "key": "AbsoluteFrequencySSB",
        }
        # {
        #     "sear": "Device.Services.FAPService.1.CellConfig.1",
        #     "PhyCellID": "100",
        #     "CellIdWithinGnb": "1",
        #     "UlLayers": "0",
        #     "UlAntennas": "4",
        #     "DlLayers": "0",
        #     "DlAntennas": "4",
        #     "PdschMcsTable": "qam256",
        #     "PuschMcsTable": "qam256",
        #     "NRARFCNDL": "513000",
        #     "NRARFCNUL": "513000",
        #     "AbsoluteFrequencySSB": "511000",
        #     "SsbPower": "-11",
        #     "FreqBandIndicator": "41",
        #     "TA": "more"
        # }
        target1 = "msg"
        target2 = "Null"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)
        except requests.exceptions.RequestException as e:
            # 请求异常时输出错误信息并返回 None
            print(f"HTTP请求失败: {e}")
            return None  # 或者返回特定的错误码，比如 -1

    if option == "set_DLBandwidth":
        url = "http://192.168.5.100:8400/public/cgi-bin/overall.cgi"
        data = {
            "flag": "set_CellConfig_info",
            "sessionid": "CZTJYZHTWBXADWRH",
            "account": "root",
            "sear": "Device.Services.FAPService.1.CellConfig.1",
            "NRARFCNDL": "513000",
            "PhyCellID": "100",
            "DLBandwidth": para,
            "PSCHPowerOffset": "db0",
            "NRARFCNUL": "513000",
            "FreqBandIndicator": "41",
            "ssbFrequency": "",
            "SsPBCHBlockPower": "-35",
            "DigitalBeamformingMode": "0",
            "AnalogBeamformingMode": "0",
            "value": para,
            "key": "DLBandwidth"
        }
        target1 = "msg"
        target2 = "Null"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)
        except requests.exceptions.RequestException as e:
            # 请求异常时输出错误信息并返回 None
            print(f"HTTP请求失败: {e}")
            return None  # 或者返回特定的错误码，比如 -1

    if option == "set_ULBandwidth":
        url = "http://192.168.5.100:8400/public/cgi-bin/overall.cgi"
        data = {
            'flag': 'set_CellConfig_info',
            'sessionid': 'CZTJYZHTWBXADWRH',
            'account': 'root',
            'sear': 'Device.Services.FAPService.1.CellConfig.1',
            'NRARFCNDL': '513000',
            'PhyCellID': '100',
            'ULBandwidth': para,
            'PSCHPowerOffset': 'db0',
            'NRARFCNUL': '513000',
            'FreqBandIndicator': '41',
            'ssbFrequency': '',
            'SsPBCHBlockPower': '-35',
            'DigitalBeamformingMode': '0',
            'AnalogBeamformingMode': '0',
            'value': para,
            'key': 'ULBandwidth'
        }
        target1 = "msg"
        target2 = "Null"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)
        except requests.exceptions.RequestException as e:
            # 请求异常时输出错误信息并返回 None
            print(f"HTTP请求失败: {e}")
            return None  # 或者返回特定的错误码，比如 -1

    if option == "set_RB":
        url = "http://192.168.5.100:8400/public/cgi-bin/ran.cgi"
        data = {
            'flag': 'set_ControlResourceSetToAddModList_list',
            'sessionid': 'CZTJYZHTWBXADWRH',
            'account': 'root',
            'sear': 'Device.Services.FAPService.1.CellConfig.1',
            'ControlResourceSetToAddModList_indexid': '1',
            'PrecoderGranularity': 'sameAsREG-bundle',
            'Duration': '2',
            'LimitedUEsInDefaultDedicatedSearchSpace': '0',
            'RbStart': '1',
            'RbNumber': para,
            'value': para,
            'key': 'RbNumber'
        }
        target1 = "msg"
        target2 = "Null"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)
        except requests.exceptions.RequestException as e:
            # 请求异常时输出错误信息并返回 None
            print(f"HTTP请求失败: {e}")
            return None  # 或者返回特定的错误码，比如 -1

    if option == "set_C_SRS1":
        url = "http://192.168.5.100:8400/public/cgi-bin/ran.cgi"
        data = {
            'flag': 'set_Config_list',
            'sessionid': 'CZTJYZHTWBXADWRH',
            'account': 'root',
            'sear': 'Device.Services.FAPService.1.CellConfig.1',
            'Config_indexid': '1',
            'ResourceType': 'periodic',
            'TransComb': '4',
            'NrofSymbols': '1',
            'RepetitionFactor': '1',
            'CycleShift': '2',
            'C_SRS': para,
            'B_SRS': '0',
            'B_hop': '0',
            'GroupOrSequenceHopping': 'neither',
            'SrsPeriod': 'sl80',
            'value': para,
            'key': 'C_SRS'
        }
        target1 = "msg"
        target2 = "Null"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)
        except requests.exceptions.RequestException as e:
            # 请求异常时输出错误信息并返回 None
            print(f"HTTP请求失败: {e}")
            return None  # 或者返回特定的错误码，比如 -1

    if option == "set_C_SRS2":
        url = "http://192.168.5.100:8400/public/cgi-bin/ran.cgi"
        data = {
            'flag': 'set_Config_list',
            'sessionid': 'CZTJYZHTWBXADWRH',
            'account': 'root',
            'sear': 'Device.Services.FAPService.1.CellConfig.1',
            'Config_indexid': '2',
            'ResourceType': 'periodic',
            'TransComb': '2',
            'NrofSymbols': '1',
            'RepetitionFactor': '1',
            'CycleShift': '2',
            'C_SRS': para,
            'B_SRS': '1',
            'B_hop': '0',
            'GroupOrSequenceHopping': 'neither',
            'SrsPeriod': 'sl160',
            'value': para,
            'key': 'C_SRS'
        }
        target1 = "msg"
        target2 = "Null"
        target3 = "Null"
        try:
            # 发送 POST 请求
            response = requests.post(url, headers=headers, data=data)
        except requests.exceptions.RequestException as e:
            # 请求异常时输出错误信息并返回 None
            print(f"HTTP请求失败: {e}")
            return None  # 或者返回特定的错误码，比如 -1


def set_100m():
    action("set_Absolute_SSB", "512910")
    action("set_DLBandwidth", "100")
    action("set_ULBandwidth", "100")
    action("set_RB", "273")
    action("set_C_SRS1", "53")
    action("set_C_SRS2", "23")


def set_80m():
    action("set_Absolute_SSB", "506910")
    action("set_DLBandwidth", "80")
    action("set_ULBandwidth", "80")
    action("set_RB", "217")


def set_60m():
    action("set_Absolute_SSB", "508830")
    action("set_DLBandwidth", "60")
    action("set_ULBandwidth", "60")
    action("set_RB", "162")
    action("set_C_SRS1", "13")
    action("set_C_SRS2", "13")


def set_40m():
    action("set_Absolute_SSB", "510990")
    action("set_DLBandwidth", "40")
    action("set_ULBandwidth", "40")
    action("set_RB", "106")


def set_30m():
    action("set_Absolute_SSB", "511950")
    action("set_DLBandwidth", "30")
    action("set_ULBandwidth", "30")
    action("set_RB", "78")


def set_20m():
    action("set_Absolute_SSB", "512910")
    action("set_DLBandwidth", "20")
    action("set_ULBandwidth", "20")
    action("set_RB", "51")


def read_speed():
    url = "http://192.168.5.100:8400/public/cgi-bin/rate.cgi"  # 替换为实际的 API 端点 URL
    data = {
        "flag": "get_mac_rate_list",
        "account": "root",
        "sessionid": "CZTJYZHTWBXADWRH",
        "sear": "Device.Services.FAPService.1.CellConfig.1"
    }

    try:
        # 发送 POST 请求
        response = requests.post(url, data=data, timeout=5)

        # 尝试解析 JSON 响应
        data = json.loads(response.text)
        rows = data.get('rows', [])

        if rows:  # 如果 rows 不为空
            result = []
            for row in rows:
                result_data = row.get('Result', '')
                result_parts = result_data.split()
                pattern = r"(\d+\.\d+)/(\d+\.\d+)"
                matches = [re.match(pattern, value) for value in result_parts]

                for match in matches:
                    if match:
                        result.append(float(match.group(1)))  # 上行吞吐量
                        result.append(float(match.group(2)))  # 下行吞吐量

            if len(result) >= 4:
                return result[:4]  # 返回前四个值
        return None  # 如果 rows 为空或未解析到足够数据，返回 None

    except (requests.exceptions.RequestException, json.JSONDecodeError):
        return None  # 如果请求或解析失败，返回 None

# read_speed()函数使用示例
# getspeed_on()
# t = 0
# while(t<10):  # 无限循环，直到手动停止
#     # 调用 read_speed 函数
#     result = read_speed()
#     # print("获取到的前四个浮动数值：", result)
#     # 等待 2 秒后再进行下一次调用
#     time.sleep(2)
#     t += 1
# getspeed_on()
# action("set_DLBandwidth", "100")
